package xcmg.device.service.agent;

import com.github.pagehelper.PageInfo;
import yb.ecp.fast.infra.util.PageHelperPlus;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xcmg.device.dao.entity.agent.ServiceBorrowOutDetailDO;
import xcmg.device.dao.entity.agent.ServiceBorrowingDO;
import xcmg.device.dao.mapper.agent.ServiceBorrowingMapper;
import xcmg.device.infra.CalcUtil;
import xcmg.device.infra.ErrorCode;
import xcmg.device.infra.ExportUtil;
import xcmg.device.service.vo.agent.ServiceBorrowOutDetailVO;
import xcmg.device.service.vo.agent.ServiceBorrowingVO;
import yb.ecp.fast.feign.FastGenClient;
import yb.ecp.fast.infra.infra.ActionResult;
import yb.ecp.fast.infra.infra.PageCommonVO;
import yb.ecp.fast.infra.infra.SearchCommonVO;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service
public class ServiceBorrowingService {
    @Autowired
    private ServiceBorrowingMapper borrowUsingMapper;
    @Autowired
    private ServiceBorrowOutDetailService serviceBorrowOutDetailService;
    @Autowired
    private FastGenClient fastGenClient;
    @Autowired
    private HttpServletResponse response;


    public ServiceBorrowingVO item(String id) {
        ServiceBorrowingDO serviceBorrowInDO = borrowUsingMapper.item(id);
        ServiceBorrowingVO serviceBorrowingVO = new ServiceBorrowingVO();
        BeanUtils.copyProperties(serviceBorrowInDO, serviceBorrowingVO);
        return serviceBorrowingVO;
    }

    public PageCommonVO detail(SearchCommonVO<ServiceBorrowingVO> condition, String orgId) {
        PageCommonVO<ServiceBorrowOutDetailVO> pageCommonVO = new PageCommonVO();
        ServiceBorrowingDO serviceBorrowInDO = borrowUsingMapper.item(condition.getFilters().getId());
        if (null == serviceBorrowInDO) {
            return pageCommonVO;
        }
        String serviceUserId = serviceBorrowInDO.getUserId();
        String materialsNo = serviceBorrowInDO.getMaterialsNo();

        PageHelperPlus.orderBy("MATERIALS_NO desc");
        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
        List<ServiceBorrowOutDetailDO> outDetailDOS = serviceBorrowOutDetailService.queryByServiceUserId(serviceUserId, materialsNo, orgId, null);
        List<ServiceBorrowOutDetailVO> resultVOList = new ArrayList<>();
        outDetailDOS.forEach(x -> {
            ServiceBorrowOutDetailVO vo = new ServiceBorrowOutDetailVO();
            BeanUtils.copyProperties(x, vo);
            resultVOList.add(vo);
        });
        pageCommonVO.setPageInfo(new PageInfo(outDetailDOS));
        pageCommonVO.setPageInfoList(resultVOList);
        return pageCommonVO;
    }


    public PageCommonVO list(SearchCommonVO<ServiceBorrowingVO> condition) {

        if (null == condition.getFilters()) {
            condition.setFilters(new ServiceBorrowingVO());
        }
        PageCommonVO<ServiceBorrowingVO> pageCommonVO = new PageCommonVO();
        PageHelperPlus.orderBy("id desc");
        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
        List<ServiceBorrowingDO> queryList = borrowUsingMapper.list(condition.getFilters());
        List<ServiceBorrowingVO> voList = new ArrayList<>();
        for (ServiceBorrowingDO entity : queryList) {
            ServiceBorrowingVO serviceBorrowInVO = new ServiceBorrowingVO();
            BeanUtils.copyProperties(entity, serviceBorrowInVO);
            serviceBorrowInVO.setSubtotal(CalcUtil.multiply(serviceBorrowInVO.getQuantity(), serviceBorrowInVO.getPrice()));
            voList.add(serviceBorrowInVO);
        }
        pageCommonVO.setPageInfo(new PageInfo(queryList));
        pageCommonVO.setPageInfoList(voList);
        return pageCommonVO;
    }

    public ErrorCode insert(ServiceBorrowingVO borrowUsingVO) {
        ActionResult<String> textResult = fastGenClient.textGuid();
        if (textResult.getCode() != ErrorCode.Success.getCode())
        {
            return ErrorCode.IllegalArument;
        }

        ServiceBorrowingDO serviceBorrowInDO = new ServiceBorrowingDO();
        BeanUtils.copyProperties(borrowUsingVO, serviceBorrowInDO);
        serviceBorrowInDO.setId(textResult.getValue());
        if (borrowUsingMapper.insert(serviceBorrowInDO) == 0) {
            return ErrorCode.Failure;
        }
        return ErrorCode.Success;
    }

    public ErrorCode update(ServiceBorrowingVO borrowUsingVO) {
        ServiceBorrowingDO serviceBorrowInDO = new ServiceBorrowingDO();
        BeanUtils.copyProperties(borrowUsingVO, serviceBorrowInDO);
        if (borrowUsingMapper.update(serviceBorrowInDO) == 0) {
            return ErrorCode.Failure;
        }
        return ErrorCode.Success;
    }

    @Transactional(rollbackFor = Exception.class)
    public ErrorCode save(ServiceBorrowingVO borrowUsingVO) {
        ServiceBorrowingVO cond = new ServiceBorrowingVO();
        cond.setUserId(borrowUsingVO.getUserId());
        cond.setMaterialsNo(borrowUsingVO.getMaterialsNo());
        List<ServiceBorrowingDO> queryList = borrowUsingMapper.list(cond);
        if (queryList.size() > 0) {
            ServiceBorrowingDO serviceBorrowInDO = new ServiceBorrowingDO();
            serviceBorrowInDO.setId(queryList.get(0).getId());
            serviceBorrowInDO.setQuantity(queryList.get(0).getQuantity().add(borrowUsingVO.getQuantity()));
            if (borrowUsingMapper.update(serviceBorrowInDO) == 0) {
                return ErrorCode.Failure;
            }
            return ErrorCode.Success;
        } else {
            return insert(borrowUsingVO);
        }

    }

    public void export(List<String> ids) throws Exception {
        List<ServiceBorrowingVO> voList = new ArrayList<>();
        for (String id : ids) {
            ServiceBorrowingDO serviceBorrowingDO = borrowUsingMapper.item(id);
            if (null == serviceBorrowingDO){
                continue;
            }
            ServiceBorrowingVO model = new ServiceBorrowingVO();
            BeanUtils.copyProperties(serviceBorrowingDO, model);
            voList.add(model);
        }
        invokeExport(voList);
    }

    public void exportAll(ServiceBorrowingVO condition) throws Exception {
        //PageHelperPlus.startPage(0, 0, "id desc");
        List<ServiceBorrowingVO> voList = new ArrayList<>();
        List<ServiceBorrowingDO> doList = borrowUsingMapper.list(condition);
        for (ServiceBorrowingDO entity : doList) {
            ServiceBorrowingVO model = new ServiceBorrowingVO();
            BeanUtils.copyProperties(entity, model);
            voList.add(model);
        }
        invokeExport(voList);
    }

    private void invokeExport(List<ServiceBorrowingVO> voList) throws Exception {
        String title = "服务借用统计数据导出";
        String[] rowsName = new String[]{"序号", "服务人员名称", "零件编码", "零件名称", "单位", "单价", "借用数量", "总额"};
        List<Object[]> dataList = new ArrayList<>();
        int i = 0;
        for (ServiceBorrowingVO serviceBorrowingVO: voList ) {
            Object[] objs = new Object[rowsName.length];
            objs[0] = i + 1;
            objs[1] = serviceBorrowingVO.getUserName();
            objs[2] = serviceBorrowingVO.getMaterialsNo();
            objs[3] = serviceBorrowingVO.getMaterialsDes();
            objs[4] = serviceBorrowingVO.getUnit();
            objs[5] = serviceBorrowingVO.getPrice();
            objs[6] = serviceBorrowingVO.getQuantity();
            objs[7] = CalcUtil.multiply(serviceBorrowingVO.getPrice() == null ? BigDecimal.ZERO : serviceBorrowingVO.getPrice()
                    ,serviceBorrowingVO.getQuantity() == null ? BigDecimal.ZERO : serviceBorrowingVO.getQuantity());
            dataList.add(objs);
            i++;
        }
        ExportUtil exportUtil = new ExportUtil(title, rowsName, dataList);
        exportUtil.export(response);
    }

    /*public void exportDetail(List<String> ids) throws Exception {
        List<ServiceBorrowingVO> voList = new ArrayList<>();
        for (String id : ids) {
            ServiceBorrowingDO serviceBorrowingDO = serviceBorrowOutDetailService.queryByServiceUserId(id);
            ServiceBorrowingVO model = new ServiceBorrowingVO();
            BeanUtils.copyProperties(serviceBorrowingDO, model);
            voList.add(model);
        }
        invokeExportDetail(voList);
    }*/

    public void exportAllDetail(ServiceBorrowingVO condition,String orgId) throws Exception {
        List<ServiceBorrowOutDetailVO> voList = new ArrayList<>();
        ServiceBorrowingDO serviceBorrowInDO = borrowUsingMapper.item(condition.getId());
        if (null == serviceBorrowInDO){
            invokeExportDetail(voList,null);
            return;
        }
        String serviceUserId = serviceBorrowInDO.getUserId();
        String materialsNo = serviceBorrowInDO.getMaterialsNo();
        String userName = serviceBorrowInDO.getUserName();
        //PageHelperPlus.startPage(0, 0, "MATERIALS_NO desc");
        List<ServiceBorrowOutDetailDO> outDetailDOS = serviceBorrowOutDetailService.queryByServiceUserId(serviceUserId, materialsNo, orgId,null);
        for (ServiceBorrowOutDetailDO entity : outDetailDOS) {
            ServiceBorrowOutDetailVO model = new ServiceBorrowOutDetailVO();
            BeanUtils.copyProperties(entity, model);
            voList.add(model);
        }
        invokeExportDetail(voList,userName);
    }

    private void invokeExportDetail(List<ServiceBorrowOutDetailVO> voList,String userName) throws Exception {
        String title = "服务借用统计详情数据导出";
        String[] rowsName = new String[]{"序号", "借用单号", "服务人员","零件编码", "零件名称", "单位", "借用数量", "出库数量", "出库状态", "单价",
                "小计","成本单价","成本小计","转销售数量","转退回数量"
        };
        List<Object[]> dataList = new ArrayList<>();
        int i = 0;
        for (ServiceBorrowOutDetailVO serviceBorrowOutDetailVO: voList ) {
            Object[] objs = new Object[rowsName.length];
            objs[0] = i + 1;
            objs[1] = serviceBorrowOutDetailVO.getBorrowOutNo();
            objs[2] = userName;
            objs[3] = serviceBorrowOutDetailVO.getMaterialsNo();
            objs[4] = serviceBorrowOutDetailVO.getMaterialsDes();
            objs[5] = serviceBorrowOutDetailVO.getUnit();
            objs[6] = serviceBorrowOutDetailVO.getQuantity();
            objs[7] = serviceBorrowOutDetailVO.getOutQuantity();
            objs[8] = getStatusDesc(serviceBorrowOutDetailVO.getStatus());
            objs[9] = serviceBorrowOutDetailVO.getPrice();
            objs[10] = serviceBorrowOutDetailVO.getSubtotalAmount();
            objs[11] = serviceBorrowOutDetailVO.getCostPrice();
            objs[12] = serviceBorrowOutDetailVO.getCostSubtotal();
            objs[13] = serviceBorrowOutDetailVO.getResaleQty();
            objs[14] = serviceBorrowOutDetailVO.getRollBackQty();
            dataList.add(objs);
            i++;
        }
        ExportUtil exportUtil = new ExportUtil(title, rowsName, dataList);
        exportUtil.export(response);
    }

    private String getStatusDesc(Integer statusId) {
        switch (statusId) {
            case 0:
            default:
                return "未出库";
            case 1:
                return "部分出库";
            case 2:
                return "已出库";
            case 3:
                return "强制结单";
        }
    }

/**根据服务人员分组，查询所有人员总金额*/
    public PageCommonVO totalAmountList(SearchCommonVO<ServiceBorrowingVO> condition) {
        PageCommonVO<ServiceBorrowingVO> pageCommonVO = new PageCommonVO();
        PageHelperPlus.orderBy("user_id desc");
        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
        List<ServiceBorrowingDO> queryList = borrowUsingMapper.totalAmountList(condition.getFilters());
        List<ServiceBorrowingVO> voList = new ArrayList<>();
        for (ServiceBorrowingDO entity : queryList) {
            ServiceBorrowingVO serviceBorrowInVO = new ServiceBorrowingVO();
            BeanUtils.copyProperties(entity, serviceBorrowInVO);
            voList.add(serviceBorrowInVO);
        }
        pageCommonVO.setPageInfo(new PageInfo(queryList));
        pageCommonVO.setPageInfoList(voList);
        return pageCommonVO;
    }

    public void exportAllTotalAmountList(ServiceBorrowingVO condition) throws Exception {
        //PageHelperPlus.startPage(0, 0, "user_id desc");
        List<ServiceBorrowingDO> doList = borrowUsingMapper.totalAmountList(condition);
        invokeExportTotalAmountList(doList);
    }

    private void invokeExportTotalAmountList(List<ServiceBorrowingDO> doList) throws Exception {
        String title = "服务借用统计总额数据导出";
        String[] rowsName = new String[]{"序号", "服务人员名称", "总额"};
        List<Object[]> dataList = new ArrayList<>();
        int i = 0;
        for (ServiceBorrowingDO serviceBorrowingDO: doList ) {
            Object[] objs = new Object[rowsName.length];
            objs[0] = i + 1;
            objs[1] = serviceBorrowingDO.getUserName();
            objs[2] = serviceBorrowingDO.getSummaryAmount();
            dataList.add(objs);
            i++;
        }
        ExportUtil exportUtil = new ExportUtil(title, rowsName, dataList);
        exportUtil.export(response);
    }
}
